package com.etop.shiro;

import java.util.Collection;

import javax.annotation.Resource;
import javax.inject.Inject;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.etop.pojo.Role;
import com.etop.pojo.User;
import com.etop.service.UserService;

/**
 * 类名：MyRealm
 * @描述：自定义Realm，进行数据源配置
 * @author Administrator
 * @date 2016年11月17日
 */
@Service
@Transactional
public class MyRealm extends AuthorizingRealm {
	
    @Resource
	private UserService userService;
    
    /**
     * 获取授权信息
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO Auto-generated method stub
		String loginName=(String) principals.getPrimaryPrincipal();
		//数据库获取此用户
		User user=userService.findByName(loginName);
		if(user!=null){
			//权限信息对象info,用来存放查出用户的所有的角色及权限
			SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
			//用户的角色集合
			info.setRoles(user.getRolesName());
			//用户的角色对应的所有权限，如果只是用角色定义访问权限
			Collection<Role> rolelist=user.getRoleList();
			for(Role role:rolelist){
				info.addStringPermissions(role.getPermissionsName());
			}
			return info;
			
			
		}
		return null;
	}
  
	/**
	 * 获取身份验证相关信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authenticationtoken) throws AuthenticationException {
		// TODO Auto-generated method stub
		//UsernamePasswordToken对象用来存放提交的用户信息
		UsernamePasswordToken token=(UsernamePasswordToken)authenticationtoken;
		//查出是否有此用户
		System.out.println(token.getUsername()+token.getPassword().toString());
		User user=userService.findByName(token.getUsername());
		if(user==null){
			
			System.out.println("user为空");
		}
		if(user!=null){
			//若存在，将此用户存放到登录验证info中
			AuthenticationInfo info=new SimpleAuthenticationInfo(user.getUsername(),
					user.getPassword(),
					getName());
			return info;
		}
		return null;
	}

}
